package com.fun.library.util;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 作者: Created by AdminFun
 * 邮箱: 614484070@qq.com
 * 创建: 2018/12/26
 * 修改: 2018/12/26
 * 版本: v1.0.0
 * 描述: 文件工具类
 */
public class Tools {

    /**
     * 从Assets文件夹中读取图片
     *
     * @param resources  资源管理
     * @param assetsName 文件名称
     */
    @Nullable
    public static Bitmap getAssetsBitmap(@NonNull Resources resources, String assetsName) {
        if (TextUtils.isEmpty(assetsName)) {
            return null;
        }
        AssetManager mAssetManager = resources.getAssets();
        InputStream open = null;
        try {
            open = mAssetManager.open(assetsName);
            return BitmapFactory.decodeStream(open);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (open != null) {
                try {
                    open.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 从项目资源加载图片
     */
    @Nullable
    public static Bitmap getProjectBitmap(@NonNull Resources resources, String source, String packName) {
        if (TextUtils.isEmpty(source)) {
            return null;
        }
        try {
            int resId = resources.getIdentifier(source, "drawable", packName);
            BitmapDrawable bitmapDrawable = (BitmapDrawable) resources.getDrawable(resId);
            return bitmapDrawable.getBitmap();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}